package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {
    @Autowired
    private StrategyThemeRepository strategyThemeRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        strategyThemeRepository.deleteById(id);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public StrategyTheme get(String id) {
        return strategyThemeRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> lists() {
        return strategyThemeRepository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {
        //创建查询对象
        Query query = new Query();
        //拿到查询对象总条数
        long count = mongoTemplate.count(query, StrategyTheme.class);
        if (count == 0){
            return Page.empty();//直接返回一个空集合
        }
        //条件
        //执行分页
        PageRequest pageRequest =PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
        query.with(pageRequest);
        //查询数据
        List<StrategyTheme> list = mongoTemplate.find(query, StrategyTheme.class);
        return new PageImpl<>(list,pageRequest,count);
    }

    @Override
    public List<StrategyTheme> findByOrderBySequence() {
        return strategyThemeRepository.findByOrderBySequence();
    }
}
